package mamikeji.liaowa.ui.fragment.favorite;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.MyFavoriteArtic;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.article.Article_DetailsActivity;
import mamikeji.liaowa.ui.adapter.ArticleRecyclerViewAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.main_view.PullLoadMoreRecyclerView;

import static android.app.Activity.RESULT_OK;

/**
 * Created by 叶寅 on 2017/9/24.
 */
public class ArticFragment extends Fragment {

    private static final int TAG_PUBLISH_FORUM = 1004;

    private static final int ARTICLE_DETAILS = 2008;


    private static final String TAG = "ArticFragment";

    private int nowPage = 1;

    @BindView(R.id.favorite_recyclerView_atic)
    PullLoadMoreRecyclerView recyclerView_Atic;
    @BindView(R.id.multiStateView_my_collection_forum_atic)
    MultiStateView multiStateViewMy_Atic;

    private RecyclerView recyclerView;
    private ArticleRecyclerViewAdapter articleRecyclerViewAdapter;

    //文章数据集
    private List<MyFavoriteArtic.DataMyFavoriteArtic> dataEntityList = new ArrayList<>();
    private List<MyFavoriteArtic.DataMyFavoriteArtic> data;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_favorite_artic, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        multiStateViewMy_Atic.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateViewMy_Atic.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        requestNetwork(1);
                    }
                });
        //获取recyclerView对象
        recyclerView = recyclerView_Atic.getRecyclerView();
        //代码设置scrollbar无效？未解决！
        recyclerView.setVerticalScrollBarEnabled(true);
        //设置下拉刷新是否可见
        recyclerView_Atic.setRefreshing(false);
        //设置是否可以下拉刷新
        recyclerView_Atic.setPullRefreshEnable(false);
        //设置是否可以上拉刷新
        //recyclerView_Atic.setPushRefreshEnable(false);
        //显示下拉刷新
        recyclerView_Atic.setRefreshing(true);
        //设置上拉刷新文字
        recyclerView_Atic.setFooterViewText("正在加载···");
        //设置上拉刷新文字颜色
        recyclerView_Atic.setFooterViewTextColor(R.color.color_app);
        articleRecyclerViewAdapter = new ArticleRecyclerViewAdapter(getActivity(), dataEntityList);
        //设置适配器
        recyclerView_Atic.setLinearLayout();
        recyclerView_Atic.setAdapter(articleRecyclerViewAdapter);
        //上拉加载下拉刷新
        recyclerView_Atic.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                nowPage += 1;
                requestNetwork(nowPage);
            }
        });
        articleRecyclerViewAdapter.setItemClickListener(new ArticleRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onCanelCollection(final int position) {
                //参数集合
                Map<String, String> formMap = new HashMap<String, String>();
                formMap.put("usercode", ForPreference.getString(ForContents.USER_CODE));

                formMap.put("articleId", dataEntityList.get(position).getArticleId() + "");

                ForHttp.setMsg(HttpApi.ROOT_PATH + "api/Article/DeleteCollectionList", formMap, new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        ForLog.i(TAG, e.getMessage());
                        ForToast.showToast(R.string.intent_error);
                    }

                    @Override
                    public void onResponse(String response) {
                        ForLog.e(TAG, response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String status = jsonObject.getString(HttpKey.STATUS);
                            if ("200".equals(status)) {
                                dataEntityList.remove(position);
                                articleRecyclerViewAdapter.notifyDataSetChanged();
                                int num = ForPreference.getInt(ForContents.USER_COLLECTION);
                                ForPreference.putInt(ForContents.USER_COLLECTION, --num);
                                ForToast.showToast(R.string.collection_delete);
                            } else {
                                ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            //跳转到文章详情页面
            @Override
            public void onStartArticleDetails(int potion) {

                Intent intent = new Intent(getActivity(), Article_DetailsActivity.class);

                intent.putExtra("articleId", dataEntityList.get(potion).getArticleId() + "");

                startActivityForResult(intent, ARTICLE_DETAILS);


            }
        });

        requestNetwork(nowPage);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == ARTICLE_DETAILS) {
                requestNetwork(nowPage);
            }
        }
    }

    //请求网络
    public void requestNetwork(final int nowPage) {
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.My_favorite_atic_category, "0");
        formMap.put(HttpKey.My_favorite_atic_page, nowPage + "");
        formMap.put(HttpKey.My_favorite_atic_pageSize, "6");
        formMap.put(HttpKey.My_favorite_usercode, ForPreference.getString(ForContents.USER_CODE));
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.My_Favorite_Artic, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                //无网络
                multiStateViewMy_Atic.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "getMain_FriendCircleData", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        MyFavoriteArtic bean = new Gson().fromJson(response, MyFavoriteArtic.class);
                        data = bean.getData();
                        if (ArticFragment.this.data != null && ArticFragment.this.data.size() > 0) {
                            if (nowPage == 1) {
                                dataEntityList.clear();
                                dataEntityList.addAll(data);
                                ForLog.i("dataList_size", dataEntityList.size() + "");
                                articleRecyclerViewAdapter.notifyDataSetChanged();
                                recyclerView_Atic.setPullLoadMoreCompleted();
                            } else {
                                ForLog.i("getMain_FriendCircleData+加载更多", response);
                                dataEntityList.addAll(data);
                                articleRecyclerViewAdapter.notifyDataSetChanged();
                                recyclerView_Atic.setPullLoadMoreCompleted();
                            }
                            //显示内容
                            multiStateViewMy_Atic.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            if (nowPage == 1) {
                                //数据为空
                                multiStateViewMy_Atic.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            } else {
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        ForToast.showToast(R.string.error_down_end);
                                        articleRecyclerViewAdapter.notifyDataSetChanged();
                                        recyclerView_Atic.setPullLoadMoreCompleted();
                                    }
                                }, 1000);
                                //显示内容
                                multiStateViewMy_Atic.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                            }
                        }
                    } else {
                        //后台错误
                        multiStateViewMy_Atic.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
